﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Text;

namespace NearChat
{
    public partial class RecuperoPassword : PhoneApplicationPage
    {
        private string mail;

        public RecuperoPassword()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            bool isCorrect=true;

            mail = mailBox.Text;

            //controllo mail
            if (mail != "")
            {
                var regEx = new System.Text.RegularExpressions.Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
                if (regEx.IsMatch(mail) == false)//non rispetta l'espressione regolare
                    isCorrect = false;//mail non corretta
            }
            else
                isCorrect = false;

            if (isCorrect)
            { 
                //faccio request PHP al DB
                Uri myDBuri1 = new Uri("http://www.nearchat.altervista.org/recuperoPassword.php");
                HttpWebRequest mailRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri1);
                mailRequest.Method = "POST";
                mailRequest.ContentType = "application/x-www-form-urlencoded";
                mailRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), mailRequest);
            } 
        }

        void GetRequestStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);

            // Create the post data
            string postData = "apikey=4nn!eSupp0rt&mail="+mail;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
        }//GetRequestStreamCallback

        void GetResponsetStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingMail(result));
            }
        }//GetResponsetStreamCallback

        void ParsingMail(string result)
        {
            if (result != "")//avvenuto errore
            {
                string[] ris = majorSplit(result);
                ris = minorSplit(ris[0]);//sono sicuro sia uno solo

                if (ris[0] == "ERRORE")
                    MessageBox.Show(ris[1]);
            }
            else 
            {
                MessageBox.Show("a mail as send to your mailbox, please check it and retry later");
            }
        }

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
    }
}